﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

/// <summary>
/// Descripción breve de ExcelExporter
/// </summary>
public class ExcelExporter
{
    public delegate object ExportFunctionModifier(object columnValue);
    private Page page;
    private Dictionary<string, ExportFunctionModifier> modifiers;
    private Dictionary<string, bool> columnVisibility;
    public ExcelExporter(Page page)
    {
        this.page = page;
        modifiers = new Dictionary<string, ExportFunctionModifier>();
        columnVisibility = new Dictionary<string, bool>();
    }
    public void AddModifier(string columnName, ExportFunctionModifier modifier)
    {
        modifiers.Add(columnName, modifier);
    }
    public void SetVisible(string columnName, bool visible)
    {
        columnVisibility.Add(columnName, visible);
    }
    private bool IsVisible(string columnName)
    {
        if (columnVisibility.ContainsKey(columnName) && columnVisibility[columnName] != null) return columnVisibility[columnName];
        else return true;//default = true

    }

    private object ApplyColumnModfiers(string columnName, object columnValue)
    {

        if (modifiers.ContainsKey(columnName) && modifiers[columnName] != null)
            return (modifiers[columnName])(columnValue);
        return columnValue;
    }

    public void Export(DataTable dt, string filename)
    {
        string attachment = "attachment; filename=" + filename + ".xls";
        page.Response.ClearContent();
        page.Response.AddHeader("content-disposition", attachment);
        page.Response.ContentType = "application/vnd.ms-excel";

        page.Response.ContentEncoding = System.Text.Encoding.Default;
        string tab = "";
        foreach (DataColumn dc in dt.Columns)
        {
            if (IsVisible(dc.ColumnName))
            {
                page.Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
        }
        page.Response.Write("\n");
        int i;
        object dataToWrite;
        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            for (i = 0; i < dt.Columns.Count; i++)
            {
                if (IsVisible(dt.Columns[i].ColumnName))
                {
                    page.Response.Write(tab);
                    dataToWrite = ApplyColumnModfiers(dt.Columns[i].ColumnName, dr[i]);
                    page.Response.Write(dataToWrite);
                    //page.Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }

            }
            page.Response.Write("\n");
        }
        page.Response.End();
    }
}
